// routes/cards/findAllByGroup.js
const express = require('express');
const pool = require('../../config/pool'); // 使用连接池
const router = express.Router();
const hadLogin = require('../../middleware/hadLogin');

router.get('/', hadLogin, (req, res) => {
    const user_id = req.user_id;
    const query = `SELECT * FROM wallets where user_id = ?`;
    pool.query(query, [user_id], (err, results) => {
        if (err) {
            return res.json({
                code: 0,
                message: '数据库错误',
                success: false
            });
        }
        if (results.length === 0) {
            // 向钱包表添加一条数据
            const insertQuery = `INSERT INTO wallets (user_id, balance) VALUES (?,?)`;
            pool.query(insertQuery, [user_id, 0], (err, results) => {
                if (err) {
                    return res.json({
                        code: 0,
                        message: '数据库错误',
                        success: false
                    });
                }
                return res.json({
                    code: 1,
                    message: '查询完成',
                    success: true,
                    data: {
                        id: results.insertId,
                        user_id: user_id,
                        balance: 0
                    }
                });
            });
        } else {
            return res.json({
                code: 1,
                message: '查询完成',
                success: true,
                data: results[0]
            });
        }
    });
});

module.exports = router;